﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Plugins.Library
{
    public static class PluginStreamHelper
    {
        public const int StreamBufferSize = 0x10000;
        public static byte[] ToByteArray(Stream stream)
        {
            int count = 0;
            List<byte> result = new List<byte>();
            try
            {
                if (stream != null)
                {
                    byte[] buffer = new byte[StreamBufferSize];
                    int bytes = 0;
                    while ((bytes = stream.Read(buffer, 0, StreamBufferSize)) > 0)
                    {
                        count += bytes;
                        for (int i = 0; i < bytes; i++)
                        {
                            result.Add(buffer[i]);
                        }
                    }
                    return result.ToArray();
                }
            }
            catch (ArgumentOutOfRangeException ex) 
            {
                PluginLog.WriteErrorSync(ex);
            }
            catch (ArgumentNullException ex)
            {
                PluginLog.WriteErrorSync(ex);
            }
            catch (ArgumentException ex)
            {
                PluginLog.WriteErrorSync(ex);
            }
            catch (IOException ex)
            {
                PluginLog.WriteErrorSync(ex);
            }
            catch (NotSupportedException ex)
            {
                PluginLog.WriteErrorSync(ex);
            }
            catch (ObjectDisposedException ex)
            {
                PluginLog.WriteErrorSync(ex);
            }
            catch (OutOfMemoryException ex)
            {
                PluginLog.WriteErrorSync(ex);
            }
            return null;
        }
    }
}
